package com.ai.aicodemather.aop;

import com.ai.aicodemather.annotation.AuthCheck;
import com.ai.aicodemather.exception.BusinessException;
import com.ai.aicodemather.exception.ErrorCode;
import com.ai.aicodemather.model.entity.User;
import com.ai.aicodemather.model.enums.UerRoleTypeEnum;
import com.ai.aicodemather.model.vo.UserLoginResponseVo;
import com.ai.aicodemather.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

import static com.ai.aicodemather.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 自定义权限切面
 */
@Aspect
@Component
public class AuthCheckAspect {

    @Resource
    private UserService userService;

    /**
     * 添加权限校验，接口级的权限
     */
    @Around("@annotation(authCheck)")
    public Object checkAuth(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取打上AuthCheck注解的方法的权限
        String requiredRole = authCheck.mustRole();
        // 从session中获取用户角色
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();
        // 获取当前登录用户，判断用户是否登录
        User loginUser = userService.getLoginUser(request);
        // 将角色转换为enum，判断权限是否为空
        UerRoleTypeEnum requiredRoleEnum = UerRoleTypeEnum.getEnumByValue(requiredRole);
        // 判断用户角色是否满足权限要求
        // 1. 不需要权限
        if (requiredRoleEnum == null) {
            return joinPoint.proceed();
        }
        UerRoleTypeEnum userRoleEnum =  UerRoleTypeEnum.getEnumByValue(loginUser.getUserRole());
        // 2. 用户无权限
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 3. 接口需要admin权限，但是用户不是admin用户
        if (UerRoleTypeEnum.ADMIN.equals(requiredRoleEnum) && !UerRoleTypeEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
